package com.hand.wfive.entity

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.hand.wfive.R

internal class ListItemDecoration @JvmOverloads constructor(
    context: Context,
    lineColor: Int = ContextCompat.getColor(context, R.color.divider),
    lineHeight: Int = 1,
    marginLeft: Int = 0
) : RecyclerView.ItemDecoration() {
    private val mPaint  : Paint = Paint()//分割线画笔
    private var lingHeight = 1 //分割线高度
    private var lineMarginLeft = 0

    init {
        mPaint.isAntiAlias = true
        mPaint.color = lineColor //设置分割线颜色
        lingHeight = dpToPx(context, lineHeight)
        lineMarginLeft = dpToPx(context, marginLeft) //设置左侧偏移量
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        outRect.bottom = lingHeight //底部偏移量
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val params = child
                .layoutParams as RecyclerView.LayoutParams
            val top = child.bottom + params.bottomMargin
            val bottom = top + lingHeight
            val left = child.left + lineMarginLeft
            val right = child.width + left - lineMarginLeft
            c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), mPaint)
        }
    }

    fun dpToPx(context: Context, dps: Int): Int {
        return Math.round(context.resources.displayMetrics.density * dps)
    }
}